<template>
    <div class="h-full relative overflow-hidden">
        <div class="h-full flex flex-col bg">
            <queryPanel v-if="!state.queryConfig.simple" :queryConfig="state.queryConfig" @flutterSend="queryTable"></queryPanel>
            <div class="p-2 w-full h-full overflow-y-auto">
                <div class="card p-4 h-full rounded">
                    <vxe-grid ref="xGrid" v-bind="state.tableConfig.gridOptions" @checkbox-all="checkBoxClickEvent" @checkbox-change="checkBoxClickEvent" @radio-change="checkBoxClickEvent" v-if="state.tableLoad">
                        <template #toolbar>
                            <div class="flex justify-between items-center pt-0 pb-3" style="min-height: 40px">
                                <a-space class="flex justify-end items-center">
                                    <a-button type="primary" @click="addRef.openModel(0)"> 新增 </a-button>
                                    <importExcel moduleName="展业任务"></importExcel>
                                    <!-- <a-button> 导出 </a-button> -->
                                    <batchConfig v-if="state.tableConfig.showBatch" ref="batchConfigRef" :tableConfig="state.tableConfig" :xGrid="xGrid" :exportData="state.exportData"></batchConfig>
                                </a-space>
                                <a-space class="flex justify-end items-center">
                                    <tableColumn class="ml-4" :xGrid="state.xGrid" :gridOptions="state.tableConfig.gridOptions"></tableColumn>
                                </a-space>
                            </div>
                        </template>
                        <template #empty> <a-list :data-source="[]" /> </template>
                    </vxe-grid>
                    <div class="p-3 h-full bg-white dark:bg-transparent" v-else>
                        <a-skeleton />
                    </div>
                </div>
            </div>
        </div>
        <!-- 弹窗 -->
        <div class="model">
            <add ref="addRef" @save="xGrid.commitProxy('query')"></add>
        </div>
    </div>
</template>
<script setup>


import { columns, flutter, batchGroup, setTreeData } from './home'
import add from './drawer/add.vue'
let state = reactive({
    addRef: undefined,
    batchConfigRef: undefined,
    xGrid: undefined,
    tableConfig: {
        tableId: '发起拜访任务',
        isTree: false,
        isPage: true,
        showBatch: true,
        showImportBut: true,
        showExportBut: false,
        selectItems: [],
        batchGroup: [],
        importUrl: '',
        exportUrl: '',
        queryUrl: '/api/zyrwSendDetail/query/list',
        gridOptions: XEUtils.clone(tableMixin, true),
    },
    //筛选
    queryConfig: {
        queryPanel: true,
        simple: false,
        flutterTitWidth: '5px',
        flutterAll: true,
        flutter: [],
    },
    query: {},
    router: useRouter(),
    store: useStore(),
    exportData: {},
})

/* =================公共函数=================== */
const checkBoxClickEvent = val => {
    if (columns[0].type === 'checkbox') {
        state.tableConfig.selectItems = [...state.xGrid.getCheckboxRecords(), ...state.xGrid.getCheckboxReserveRecords()]
        state.batchConfigRef.setSelectItems(state.tableConfig.selectItems)
    } else if (columns[0].type === 'radio') {
        state.tableConfig.selectItems = [val.row]
    }
}
const queryTable = (datas, datasAll) => {
    state.exportData = datas
    if (datas.taskSendTime) {
        datas.taskSendTime = datas.taskSendTime.join()
    }
    if (datas.deadline) {
        datas.deadline = datas.deadline.join()
    }
    // if (datas.director) {
    //     datas.director = datasAll[3].name
    // }
    // if (datas.department) {
    //     datas.department = datasAll[2].name
    // }
    state.queryConfig.flutter = datas
    // if (state.queryConfig.flutter.director) {
    //     const promiseArr = state.queryConfig.flutter.director.map(item => {
    //         return axios.postJson('/api/dingtalk/topapi/v2/user/get', { userid: item })
    //     })
    //     const resArr = await Promise.all(promiseArr)
    //     const userName = resArr.map(res => {
    //         return res.data.result.name
    //     })
    //     console.log(userName)
    //     state.queryConfig.flutter.director = userName.join()
    //     console.log(state.queryConfig.flutter.director)
    //     console.log(typeof state.queryConfig.flutter.director)
    //     console.log(11111)
    // }
    // if (state.queryConfig.flutter.department) {
    //     const promiseArr = state.queryConfig.flutter.department.map(item => {
    //         return axios.postJson('/api/dingtalk/topapi/v2/department/get', { dept_id: item })
    //     })
    //     const resArr = await Promise.all(promiseArr)
    //     const deptName = resArr.map(res => {
    //         return res.data.result.name
    //     })
    //     state.queryConfig.flutter.department = deptName.join()
    //     console.log(state.queryConfig.flutter.department)
    //     console.log(typeof state.queryConfig.flutter.department)
    // }
    console.log(state.queryConfig.flutter)
    state.xGrid.commitProxy('query')
}
/* =================初始化页面=================== */
createTable()
function createTable() {
    if (state.queryConfig.queryPanel) state.queryConfig.flutter = flutter
    if (state.tableConfig.showBatch) state.tableConfig.batchGroup = batchGroup
    createColumnsFull()
    createTableFull()
    state.tableLoad = true

    // setTimeout(() => {
    //     console.log(state.xGrid)
    //     state.xGrid.setTheme('dark')
    // }, 500);
}
//创建表头数据
function createColumnsFull() {
    state.tableConfig.gridOptions.columns = columns
}

//创建表格
function createTableFull() {
    state.tableConfig.gridOptions.id = state.tableConfig.tableId
    state.tableConfig.gridOptions.rowConfig.keyField = 'id'
    state.tableConfig.gridOptions.proxyConfig.props.result = 'data.records'
    if (!state.tableConfig.isPage) state.tableConfig.gridOptions.pagerConfig.autoHidden = true
    if (state.tableConfig.isTree) {
        state.tableConfig.gridOptions.proxyConfig.props.result = 'data'
        state.tableConfig.gridOptions.proxyConfig.props.total = 'total'
        state.tableConfig.gridOptions.checkboxConfig.checkStrictly = false
        if (!state.tableConfig.isPage) state.tableConfig.gridOptions.pagerConfig.autoHidden = true
        state.tableConfig.gridOptions.treeConfig = {
            transform: true,
            rowField: 'id',
            parentField: 'parentId',
            children: 'children',
            reserve: false,
        }
    }
    state.tableConfig.gridOptions.loading = true
    state.tableConfig.gridOptions.proxyConfig.ajax = {
        query: ({ page, sorts }) => {
            const queryParams = {
                pageNo: page.currentPage,
                pageSize: page.pageSize,
            }
            Object.assign(queryParams, state.query, state.queryConfig.flutter)
            if (sorts[0]) queryParams.sort = sorts[0].property + ',' + sorts[0].order
            return new Promise((resolve, reject) => {
                axios
                    .postJson(`${state.tableConfig.queryUrl}`, queryParams)
                    .then(res => {
                        state.tableConfig.gridOptions.loading = false
                        if (state.tableConfig.isPage) {
                            if (state.tableConfig.isTree) {
                                res.data.data = XEUtils.toTreeArray(res.data.data)
                            }
                        } else {
                            if (state.tableConfig.isTree) res = setTreeData(res)
                        }
                        resolve(res)
                    })
                    .catch(err => {
                        state.tableConfig.gridOptions.loading = false
                        reject()
                    })
            })
        },
    }
}

const goDetail = row => {
    state.router.push({
        path: '/detail',
        query: {
            id: row.id,
        },
    })
}

const remove = row => {
    Modal.confirm({
        title: '提示',
        content: `删除后无法撤销，是否确认删除？`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {},
        onCancel() {
            console.log('Cancel')
        },
    })
}

//导出方法给父组件调用
defineExpose({})
const { xGrid, addRef, batchConfigRef } = toRefs(state)
</script>
